<?php

namespace app\model\Dao\Mysql;

use app\lib\Helper;
use think\facade\Db;
use think\Model;

class Base extends Model{

    /**
     * 更新或新增
     *
     * @param array $wh
     * @param array $data
     * @return \think\Model
     */
    public static function updateOrCreate($wh, $data){
        return self::where($wh)->findOrEmpty()->save($data);
    }

    /**
     * 根据主键更新或新增
     *
     * @param array $data 数据列表(多条)
     * @param string $pk 主键字段
     * @return \think\Model
     */
    public static function updateOrCreateByPk($data, $pk = 'id'){
        foreach (explode(',', $pk) as $field) {
            $wh[$field] = $data[$field];
        }
        return self::updateOrCreate($wh, $data);
    }

    /**
     * 通过主键更新或新增(批量)
     *
     * @param array $list
     * @param string $pk
     * @return void
     */
    public static function updateOrCreateByPkBatch($list, $pk = 'id'){
        foreach ($list as $one) {
            self::updateOrCreateByPk($one, $pk);
        }
    }

    /**
     * 获取类型列表
     *
     * @return array
     */
    public static function typeSelectData($arr): array {
        $data = [];
        foreach ($arr as $key => $value) {
            $data[] = [ 'key' => $key, 'label' => $value ];
        }
        return $data;
    }

    /**
     * 批量新增数据（带分块）
     *
     * @param array $list 
     * @param integer $block
     * @return void
     */
    public function addAll(array $list, $block = 500)
    {
        $blocked = Helper::goBlock($list, $block);
        foreach ($blocked as $some) {
            $rs = Db::name($this->name)->insertAll($some);
        }
        return $rs;
    }

    /**
     * 批量新增数据（带分块）
     *
     * @param  $tableOj
     * @param array $list
     * @param integer $block
     * @return 
     */
    public static function insertAll($tableOj, $list, $block=500)
    {
        $blocked = Helper::goBlock($list, $block);
        foreach ($blocked as $some) {
            $rs = Db::name($tableOj->name)->insertAll($some);
        }
        return $rs;
    }
}